package api

import (
	"net/http"
	"strconv"

	"gitee.com/zatto/project/tree/master/vblog/api/apps/blog"
	"github.com/gin-gonic/gin"
)

func (h *handler) CreateBlog(c *gin.Context) {
	// 构建请求对象
	req := blog.NewCreateBlogRequest()
	if err := c.BindJSON(req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
		return
	}

	// 执行业务模块
	ins, err := h.svc.CreateBlog(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	// 返回响应
	c.JSON(http.StatusOK, gin.H{"data": ins})
}

func (h *handler) QueryBlog(c *gin.Context) {
	req, err := blog.NewQueryBlogRequestFromGin(c)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
		return
	}

	set, err := h.svc.QueryBlog(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, set)
}

func (h *handler) DescribeBlog(c *gin.Context) {
	strId := c.Param("id")
	id, err := strconv.Atoi(strId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
		return
	}
	req := blog.NewDescribeBlogRequest(id)

	ins, err := h.svc.DescribeBlog(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, ins)

}

func (h *handler) updateBlog(c *gin.Context, mode blog.UpdateMode) {
	strId := c.Param("id")
	id, err := strconv.Atoi(strId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
		return
	}
	cReq := blog.NewCreateBlogRequest()
	if err := c.BindJSON(cReq); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
		return
	}
	req := blog.NewUpdateBlogRequest(mode, id, cReq)

	ins, err := h.svc.UpdateBlog(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, ins)
}

func (h *handler) PutBlog(c *gin.Context) {
	h.updateBlog(c, blog.PUT)
}

func (h *handler) PatchBlog(c *gin.Context) {
	h.updateBlog(c, blog.PATCH)
}

func (h *handler) DeleteBlog(c *gin.Context) {
	strId := c.Param("id")
	id, err := strconv.Atoi(strId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
		return
	}
	req := blog.NewDeleteBlogRequest(id)

	ins, err := h.svc.DeleteBlog(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, ins)
}
